//
//  GTQSelectCityViewController.m
//  GTQCitySelector
//
//  Created by 光头强 on 16/7/21.
//  Copyright © 2016年 Ls. All rights reserved.
//

#import "GTQSelectCityViewController.h"
#import "UIBarButtonItem+GTQInit.h"
#import "ChineseString.h"
#import "ChineseToPinyin.h"
#import "GTQNoticeHeaderView.h"
#import "AchiveTool.h"
#import "GTQHistoryCell.h"

#define fileName @"historyCitys.src"      //归档文件名

#define ScreenWidth    [UIScreen mainScreen].bounds.size.width

@interface GTQSelectCityViewController ()<UITableViewDataSource, UITableViewDelegate, GTQHistoryCellDelegate, UISearchBarDelegate>
@property (weak, nonatomic) IBOutlet UISearchBar *citySearchBar;
@property (weak, nonatomic) IBOutlet UITableView *cityTableView;

/** city数据源 */
@property (nonatomic, strong) NSMutableArray *titleArr;
@property (nonatomic, strong) NSMutableArray *dataArr;

/** 历史记录的数据源 */
@property (nonatomic, strong) NSMutableArray *hisCitys;
/** 搜索结果显示 */
@property (nonatomic, strong) UITableView *searchResultTbView;
/** 搜索时调用的数据源 */
@property (nonatomic,strong) NSMutableArray *datas;
@property (nonatomic, strong) NSMutableArray *searchArr;
/** 定位的城市 */
//@property (nonatomic, copy) NSString *locationCity;
/** 表头提示文字 */
@property (nonatomic, strong) UILabel *headerLabel;
@end

@implementation GTQSelectCityViewController
#pragma mark - 初始化数据源
- (void)loadData {
    NSMutableArray *array = [NSMutableArray array];
    //从本地获取数据
    NSDictionary *dict = [[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"address" ofType:@"plist"]];
    NSArray *arr = [dict objectForKey:@"address"];
    for (NSDictionary *dict in arr) {
        NSArray *newArr = [dict objectForKey:@"sub"];
        for (NSDictionary *cDict in newArr) {
            [array addObject:[cDict objectForKey:@"name"]];
        }
    }
    
    self.titleArr = [ChineseString IndexArray:array];
    self.dataArr = [ChineseString LetterSortArray:array];
//    NSLog(@"%@",_titleArr);
//    NSLog(@"%@",_dataArr);
    
    //从归档文件中获访问历史取数据源
    _hisCitys = [NSMutableArray arrayWithArray:[AchiveTool unAchiveWithFileName:fileName]];

}

/**
 *  搜索的源数据
 */
- (void)loadSearchDatas {
    _datas = [NSMutableArray array];
    for (int i = 0; i < self.dataArr.count; i++) {
        NSArray *arr = [self.dataArr objectAtIndex:i];
        for (int j = 0;j < arr.count; j++) {
            [_datas addObject:[arr objectAtIndex:j]];
        }
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setupNavigationItem];
    
    [self loadData];
    
    [self loadSearchDatas];//搜索的源数据
    
    [self setupView];
}

- (void)setupView {
    self.cityTableView.delegate = self;
    self.cityTableView.dataSource = self;
    [self.cityTableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"CityCell"];
    
    GTQNoticeHeaderView *header = [[GTQNoticeHeaderView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 44)];
    header.block = ^(NSString *city){
        NSLog(@"我真的一脸懵比");
        // 选中某城市
        [self didSelectedCity:city];
    };
    self.cityTableView.tableHeaderView = header;
    
    self.citySearchBar.delegate = self;
    _searchResultTbView = [[UITableView alloc] initWithFrame:CGRectMake(0, _cityTableView.frame.origin.y, ScreenWidth, _cityTableView.frame.size.height + 64) style:UITableViewStylePlain];
    _searchResultTbView.delegate = self;
    _searchResultTbView.dataSource = self;
    _searchResultTbView.alpha = 0;
    [_searchResultTbView registerClass:[GTQHistoryCell class] forCellReuseIdentifier:@"historyCell"];
    [self.view addSubview:_searchResultTbView];
    
    // 注册cell
    [self.cityTableView registerClass:[GTQHistoryCell class] forCellReuseIdentifier:@"histroyCell"];
    [self.cityTableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cityCell"];
    [self.searchResultTbView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"searchCell"];
}

- (void)setupNavigationItem {
    self.title = @"定位";
    
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem barButtonItemWithImage:@"close"  highlightImage:nil target:self action:@selector(close)];
}

- (void)setSearchTableViewHidden:(BOOL)hidden {
    if (!hidden) {
        [UIView animateWithDuration:0.5 animations:^{
            _searchResultTbView.alpha = 1;
        }];
    } else {
        [UIView animateWithDuration:0.3 animations:^{
            _searchResultTbView.alpha = 1;
        } completion:^(BOOL finished) {
            _searchResultTbView.alpha = 0;
        }];
    }
}

- (void)close {
    [self.navigationController dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - UITableview的代理方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tableView == _searchResultTbView) {
        return _searchArr.count;
    } else {
        if (self.hisCitys.count == 0) {
            NSArray *arr = [_dataArr objectAtIndex:section];
            return [arr count];
        }
        
        return section == 0 ? 1 : [[_dataArr objectAtIndex:section - 1] count];
    }
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (tableView == _searchResultTbView) {
        return 1;
    } else {
        if (self.hisCitys.count == 0) {
            return _titleArr.count;
        }
        
        return _titleArr.count + 1;//有历史记录
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == _searchResultTbView) {
        return 44;
    } else {
        if (self.hisCitys.count == 0) {
            return 44;
        } else {
            //有历史记录
            if (indexPath.section == 0) {
                return 84;
            } else {
                return 44;
            }
        }
    }
}
//返回cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == _searchResultTbView) {
        static NSString *searchCellId = @"searchCell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:searchCellId];
        
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:searchCellId];
        }
        cell.textLabel.textColor = [UIColor darkGrayColor];
        
        cell.textLabel.text = [_searchArr objectAtIndex:indexPath.row];
        
        return cell;
    } else {
        if (self.hisCitys.count == 0) {
            UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CityCell" forIndexPath:indexPath];
            cell.textLabel.textColor = [UIColor darkGrayColor];
            
            cell.textLabel.text = _dataArr[indexPath.section][indexPath.row];
            
            return cell;
        } else {
            if (indexPath.section == 0) {
                GTQHistoryCell *cell = [[GTQHistoryCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"historyCell"];
                cell.delegate = self;
                [cell setHistroys:self.hisCitys];
                
                return cell;
                
            } else {
                UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CityCell" forIndexPath:indexPath];
                cell.textLabel.textColor = [UIColor darkGrayColor];
                
                cell.textLabel.text = _dataArr[indexPath.section-1][indexPath.row];
                
                return cell;
            }
        }
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *title = nil;
    if (tableView == _searchResultTbView) {
        title = _searchArr[indexPath.row];
    } else {
        if (self.hisCitys.count == 0) {
            title = _dataArr[indexPath.section][indexPath.row];
        } else {
            if (indexPath.section == 0) {
                return;
            }
            
            title = _dataArr[indexPath.section - 1][indexPath.row];
        }
    }

    NSLog(@"title:%@",title);
    //选中城市
    [self didSelectedCity:title];
}

//返回每组的标题
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (tableView == _searchResultTbView) {
        return nil;
    }
    UIView *bgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 35)];
    bgView.backgroundColor = RGBColor(240, 240, 240);
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(15, 0, ScreenWidth-15, 35)];
    label.textAlignment = NSTextAlignmentLeft;
    label.textColor = [UIColor colorWithRed:143/255.0 green:144/255.0 blue:145/255.0 alpha:1.0];
    [bgView addSubview:label];
    if (self.hisCitys.count == 0) {
        label.text = [_titleArr objectAtIndex:section];
    } else {
        if (section == 0) {
            label.text = @"历史访问城市";
        } else {
            label.text = [_titleArr objectAtIndex:section - 1];
        }
    }
    
    return bgView;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (tableView == _searchResultTbView) {
        return 0;
    }
    return 35;
}

//返回每组的索引
-(NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView{
    if (tableView == _searchResultTbView) {
        return nil;
    }
    
    NSMutableArray *indexs = [NSMutableArray arrayWithArray:_titleArr] ;
    if (self.hisCitys.count != 0) {
        [indexs insertObject:@"$" atIndex:0];
    }
    return indexs;
}

#pragma mark - UISearchBar的代理方法
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    if (searchBar.text.length == 0) {
        [self setSearchTableViewHidden:YES]; //控制搜索列表的隐现
        
    }else{
        [self setSearchTableViewHidden:NO];
        //       NSPredicate *resultPredicate = [NSPredicate  predicateWithFormat:@"SELF contains[cd] %@",searchText];
        //        _searchArr =(NSMutableArray *)[self.datas filteredArrayUsingPredicate:resultPredicate];
        
        _searchArr = [NSMutableArray array];
        for (int i = 0; i < _datas.count; i++) {
            if ([[ChineseToPinyin pinyinFromChiniseString:_datas[i]] hasPrefix:[searchText uppercaseString]] || [_datas[i] hasPrefix:searchText]) {
                [_searchArr addObject:[_datas objectAtIndex:i]];
            }
        }
        
        [_searchResultTbView reloadData];
    }
}

- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar
{
    searchBar.showsCancelButton = YES;
    
    return YES;
}

#pragma mark - 结束编辑
- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar {
    searchBar.showsCancelButton = NO;
}
//点击搜索框上的 取消按钮时 调用
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
    NSLog(@"cancle clicked");
    _citySearchBar.text = @"";
    [self setSearchTableViewHidden:YES];
    [_citySearchBar resignFirstResponder];
}
#pragma mark - UIScrollerView的代理方法
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    if ([scrollView isEqual:_searchResultTbView]) {
        [_citySearchBar endEditing:YES];
    }
    
    _citySearchBar.text = @"";
    [_citySearchBar endEditing:YES];
}

#pragma mark - GTQHistoryCell代理方法点击了Label
- (void)HistoryCell:(GTQHistoryCell *)historyCell didClickWithLabelText:(NSString *)text {
    NSLog(@"代理方法点击了Label%@",_hisCitys);
    [self didSelectedCity:text];
}


#pragma mark - 存储历史数据数组并且归档
- (void)saveHistroysWithText:(NSString *)text {
    [self.hisCitys insertObject:text atIndex:0];
    
    if (self.hisCitys.count == 2) {
        if ([text isEqualToString:[self.hisCitys objectAtIndex:1]]) {
            [self.hisCitys removeLastObject];
        }
    }
    
    if (self.hisCitys.count ==3) {
        
        if ([text isEqualToString:[_hisCitys objectAtIndex:2]]) {
            [_hisCitys removeLastObject];
        }
        if ([text isEqualToString:[_hisCitys objectAtIndex:1]]) {
            [_hisCitys removeObjectAtIndex:1];
            
        }
    }
    if (_hisCitys.count>3) {
        
        if ([text isEqualToString:[_hisCitys objectAtIndex:2]]) {
            [_hisCitys removeObjectAtIndex:2];
            
        }
        else if ([text isEqualToString:[_hisCitys objectAtIndex:1]])
        {
            [_hisCitys removeObjectAtIndex:1];
        }
        else
        {
            [_hisCitys removeObjectAtIndex:3];
        }
    }

    [AchiveTool achiveWithArray:_hisCitys FileName:fileName];
}

#pragma mark - 选中城市后
- (void)didSelectedCity:(NSString *)city {
    if (self.delegate && [self.delegate respondsToSelector:@selector(didSelectedTitle:)]) {
        [_delegate didSelectedTitle:city];
    }
    
    //保存到历史记录
    [self saveHistroysWithText:city];
    
    //退出页面
    [self.navigationController dismissViewControllerAnimated:YES completion:nil];
}

@end
